package logger

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

func isWindows() bool {
	return runtime.GOOS == "windows"
}

func color(color int, str string) string {
	if isWindows() {
		return str
	}

	return fmt.Sprintf("\033[%dm%s\033[0m", color, str)
}

// rgb 颜色用法，参考这个库：https://github.com/guidao/gotermcolor/blob/master/gotermcolor.go
func colorRGB(r, g, b int, str string) string {
	if isWindows() {
		return str
	}

	begin := "\033["
	end := "\033[0m"
	forecolor := fmt.Sprintf("38;2;%d;%d;%d", r, g, b)
	return begin + fmt.Sprintf("%sm", forecolor) + str + end
}

func ColorRGB(r, g, b int, str string) string {
	return colorRGB(r, g, b, str)
}

func getBase(level string, skip int) (s string) {
	prefix := getPrefix()
	if config.Pad > 0 {
		prefix = PadStart(getPrefix(), config.Pad)
	}
	s = fmt.Sprintf("%s %s %s ", getTime(), level, prefix)
	_, file, line, _ := runtime.Caller(skip)

	if config.ShowLine {
		file = shorterFile(file)
		if file != "" {
			s = fmt.Sprintf("%s%s:%s ", s, Green(file), Yellow(intToString(line)))
		}
	}

	return
}

func getPrefix() string {
	return HiCyan(config.Name)
}

func getTime() string {
	return HiBlue(time.Now().Format("2006-01-02 15:04:05.000"))
}

func intToString(number int) string {
	return fmt.Sprintf("%d", number)
}

func shorterFile(file string) string {
	i := strings.Index(file, "@")
	if i >= 0 {
		return ""
	}

	d, err := os.Getwd()
	if err != nil {
		return file
	}

	realPath, err2 := filepath.EvalSymlinks(d)
	if err2 != nil {
		return file
	}

	path := realPath + "/"

	if !strings.Contains(file, realPath) {
		return file
	}

	return file[len(path):]
}
